package org.ecype.diego;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;

public class EntityDirProcessor extends EntityProcessor {

	private final Entity entity;

    public EntityDirProcessor(Entity entity) {
		super(entity, URI_DIR);
        this.entity = entity;
	}

	@Override
	public Uri insert(Uri uri, Uri notifyUri, ContentValues values) {
		return insertHelper(uri, notifyUri, values);
	}
	
	@Override
	public int bulkInsert(Uri uri, Uri notifyUri, ContentValues[] values) {
	    return bulkInsertHelper(uri, notifyUri, values); 
	}

	@Override
	public Cursor query(Uri uri, Uri notifyUri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		return queryHelper(uri, notifyUri, projection, selection, selectionArgs, sortOrder);
	}

	@Override
	public int delete(Uri uri, Uri notifyUri, String selection, String[] selectionArgs) {
        if (!entity.getReferencesToChild().isEmpty()) {
            String removingIds = getRemovingIds(uri, selection, selectionArgs);
            if (!TextUtils.isEmpty(removingIds)) {
    			for (Reference reference : entity.getReferencesToChild()) {
    				String childSelection = buildSelectionForChildTableWhereForeignKeysAre(reference, removingIds);
    				if (reference.isCascadeRemove()) {
    					provider.delete(reference.getChild().getUri(), childSelection, null);
    				} else {
    					//set null
    					ContentValues values = new ContentValues();
    					values.put(reference.getLinkToParent(), (String) null);
    					provider.update(reference.getChild().getUri(), values, childSelection, null);
    				}
    			}
    			resolver.notifyChange(entity.getUri(), null);
            }
        }
	    int deleted = deleteHelper(uri, notifyUri, selection, selectionArgs);
		return deleted;
	}
	
	private String buildSelectionForChildTableWhereForeignKeysAre(Reference reference, String keys) {
		return reference.getLinkToParent() + " IN (" + keys + ")";
	}
	
	private String getRemovingIds(Uri uri, String selection, String[] selectionArgs) {
		String result = null;
		Cursor cursor = provider.query(uri, new String[] { entity.getIdColumn().getName() }, selection, selectionArgs, null);
		if (cursor != null) {
			if (cursor.moveToFirst()) {
				StringBuilder builder = new StringBuilder();
				do {
					builder.append(cursor.getLong(0)).append(',');
				} while (cursor.moveToNext());
				builder.deleteCharAt(builder.length() - 1);
				result = builder.toString();
			}
			cursor.close();
		}
		return result;
	}
	
	@Override
	public int update(Uri uri, Uri notifyUri, ContentValues values, String selection, String[] selectionArgs) {
		return updateHelper(uri, notifyUri, values, selection, selectionArgs);
	}

}
